package com.banzhi.shop.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.activity.ApplicationActivity;
import com.banzhi.shop.activity.ChoiceAddressActivity;
import com.banzhi.shop.activity.CityPartnerActivity;
import com.banzhi.shop.activity.GroupingProfitActivity;
import com.banzhi.shop.activity.IncomeStatementActivity;
import com.banzhi.shop.activity.MyGroupingActivity2;
import com.banzhi.shop.activity.MyShouhouActivity;
import com.banzhi.shop.activity.MyUpPeopleActivity;
import com.banzhi.shop.activity.NewLoginActivity;
import com.banzhi.shop.activity.NewsActivity;
import com.banzhi.shop.activity.OrderManageActivity;
import com.banzhi.shop.activity.PartnerApplicationActivity;
import com.banzhi.shop.activity.PersonDetailActivity;
import com.banzhi.shop.activity.RemainingTimeActivity;
import com.banzhi.shop.activity.RequestWithdrawActivity;
import com.banzhi.shop.activity.SettingActivity;
import com.banzhi.shop.activity.ShoppingCartActivity;
import com.banzhi.shop.activity.ShouHouActivity;
import com.banzhi.shop.data.BeCityPartnersData;
import com.banzhi.shop.entity.My.UserInfo_Data;
import com.banzhi.shop.model.CallBack.BeCityPartnersCallBack;
import com.banzhi.shop.model.CallBack.MyFrgCallBack;
import com.banzhi.shop.model.IMyFrgModel;
import com.banzhi.shop.model.Impl.BeCityPartnersImpl;
import com.banzhi.shop.model.Impl.MyFrgImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.view.BadgeView;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import static com.banzhi.shop.base.BaseActivity.finishAllActivity;

/**
 * 我的
 */

public class MyFrg extends Fragment implements View.OnClickListener, MyFrgCallBack, SwipeRefreshLayout.OnRefreshListener, BeCityPartnersCallBack {

    public static final String TAG = "MyFrg";
    /**
     * 设置
     */
    private ImageView ivsetting;
    /**
     * 消息
     */
    private ImageView ivnews;
    /**
     * 我的购物车
     */
    private LinearLayout llmuCart;
    /**
     * 头像
     */
    private ImageView ivtouxiang;
    /**
     * 地址
     */
    private LinearLayout lladdress;
    /**
     * 优惠券
     */
    private LinearLayout llyouhui;
    /**
     * 收益记录
     */
    private LinearLayout llshouyi;
    /**
     * 申请提现
     */
    private LinearLayout lltixian;
    /**
     * 我的推荐人信息
     */
    private LinearLayout lluppeople;
    /**
     * 我的售后
     */
    private LinearLayout llshouhou;
    /**
     * 姓名
     */
    private TextView tvname;
    /**
     * 可用金额
     */
    private TextView tvkeyong;
    /**
     * 累计金额
     */
    private TextView tvleiji;
    /**
     * 代发金额
     */
    private TextView tvdaifa;
    /**
     * 管理收益
     */
    //private TextView tvguanli;
    /**
     * 跳转到我的资料
     */
    private ImageView ivright;
    private IMyFrgModel model;
    private UserInfo_Data data;
    private BadgeView badgeView;
    //  private TextView tvtime;
    private View view;
    //  private TextView textView;
    private SwipeRefreshLayout swipeRefreshLayout;
    //  private TextView tv_shopNum;

    private LinearLayout llPartner;
    private BeCityPartnersImpl mBeCityPartnersModel;
    private BeCityPartnersData mPartnersData;

    private String mCheck;
    private String mIspay;
    private String mCode;
    private String mCode1;
    private LinearLayout mLlGrouping;
    private LinearLayout mLlTime;
    private LinearLayout mLlGroupProfit;
    private LinearLayout mLlOrderManage;
    private LinearLayout mL;
    private LinearLayout mLl;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frg_my2, container, false);
        initView();
        setListeners();
        model = new MyFrgImpl();
        mBeCityPartnersModel = new BeCityPartnersImpl();
        mBeCityPartnersModel.beCityPartners(this);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        model.getData(this);
        model.getNewNumber(this);
    }

    private void setListeners() {
        ivsetting.setOnClickListener(this);
        llmuCart.setOnClickListener(this);
        lladdress.setOnClickListener(this);
        ivtouxiang.setOnClickListener(this);
        ivright.setOnClickListener(this);
        //    llyouhui.setOnClickListener(this);
        llshouyi.setOnClickListener(this);
        ivnews.setOnClickListener(this);
        lltixian.setOnClickListener(this);
        lluppeople.setOnClickListener(this);
        llshouhou.setOnClickListener(this);
        llPartner.setOnClickListener(this);
        mLlTime.setOnClickListener(this);
        mLlGrouping.setOnClickListener(this);
        mLlGroupProfit.setOnClickListener(this);
        mLlOrderManage.setOnClickListener(this);
        tvname.setOnClickListener(this);
    }

    private void initView() {
        mL = (LinearLayout) view.findViewById(R.id.ll_Gone);
        mLl = (LinearLayout) view.findViewById(R.id.ll_Gone2);
        mLlGrouping = (LinearLayout) view.findViewById(R.id.ll_grouping);
        llPartner = (LinearLayout) view.findViewById(R.id.llPartner);
        ivsetting = (ImageView) view.findViewById(R.id.img_setting);
        ivnews = (ImageView) view.findViewById(R.id.img_news);
        llmuCart = (LinearLayout) view.findViewById(R.id.ll_mycart);
        ivtouxiang = (ImageView) view.findViewById(R.id.iv_touxiang);
        tvname = (TextView) view.findViewById(R.id.tv_name);
        tvkeyong = (TextView) view.findViewById(R.id.tv_keyong);
        tvleiji = (TextView) view.findViewById(R.id.tv_leiji);
        tvdaifa = (TextView) view.findViewById(R.id.tv_daifa);
        //   tvguanli = (TextView) view.findViewById(R.id.tv_guanli);
        lladdress = (LinearLayout) view.findViewById(R.id.ll_address);
        //    llyouhui = (LinearLayout) view.findViewById(R.id.ll_youhuiquan);
        llshouyi = (LinearLayout) view.findViewById(R.id.ll_shouyi);
        lltixian = (LinearLayout) view.findViewById(R.id.ll_tixian);
        lluppeople = (LinearLayout) view.findViewById(R.id.ll_up_people);
        llshouhou = (LinearLayout) view.findViewById(R.id.ll_shouhou);
        ivright = (ImageView) view.findViewById(R.id.iv_right);
        //  tvtime = (TextView) view.findViewById(R.id.tv_time);
        mLlTime = (LinearLayout) view.findViewById(R.id.ll_time);
        badgeView = new BadgeView(getContext());
        //   textView = (TextView) view.findViewById(R.id.view3);
        //   tv_shopNum = (TextView) view.findViewById(R.id.tv_shopNum);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.srl_listview);
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        swipeRefreshLayout.setColorSchemeResources(R.color.themeColor);
        swipeRefreshLayout.setOnRefreshListener(this);
        mLlGroupProfit = (LinearLayout) view.findViewById(R.id.ll_group_profit);
        mLlOrderManage = (LinearLayout) view.findViewById(R.id.ll_order_manage);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_name:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent setintent = new Intent(getActivity(), SettingActivity.class);
                    startActivity(setintent);
                } else {

                    showLoginPopupWindow();
                }
                break;
            case R.id.img_setting:
             /*   if (!"".equals(MyApp.loginMessage.getString("token",""))) {*/
                Intent setintent = new Intent(getActivity(), SettingActivity.class);
                startActivity(setintent);
             /*   }else {
                    showLoginPopupWindow();
                }*/

                break;
            //购物车
            case R.id.ll_mycart:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent MCintent = new Intent(getActivity(), ShoppingCartActivity.class);
                    startActivity(MCintent);
                } else {
                    showLoginPopupWindow();
                }

                break;
            //选择地址
            case R.id.ll_address:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent CAintent = new Intent(getActivity(), ChoiceAddressActivity.class);
                    startActivity(CAintent);
                } else {
                    showLoginPopupWindow();
                }

                break;
            //个人头像
            case R.id.iv_touxiang:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent PDintent = new Intent(getActivity(), PersonDetailActivity.class);
                    startActivity(PDintent);
                } else {
                    showLoginPopupWindow();
                }

                break;
            case R.id.iv_right:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent Pintent = new Intent(getActivity(), PersonDetailActivity.class);
                    startActivity(Pintent);
                } else {
                    showLoginPopupWindow();
                }

                break;
            //优惠券
          /*  case R.id.ll_youhuiquan:
                Intent DCintent = new Intent(getActivity(), DiscountCouponActivity.class);
                startActivity(DCintent);
                break;*/
            case R.id.ll_time:
                //跳转到剩余时间
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent intent1 = new Intent(getActivity(), RemainingTimeActivity.class);
                    //  intent1.putExtra("shopertime",data.getShopertime());
                    startActivity(intent1);
                } else {
                    showLoginPopupWindow();
                }

                break;
            case R.id.ll_grouping:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    //跳转到我的拼团
                    Intent intent2 = new Intent(getActivity(), MyGroupingActivity2.class);
                    startActivity(intent2);
                } else {
                    showLoginPopupWindow();
                }

                break;

            //收益明细
            case R.id.ll_shouyi:

                //跳转到剩余时间
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent SJintent = new Intent(getActivity(), IncomeStatementActivity.class);
                    startActivity(SJintent);
                } else {
                    showLoginPopupWindow();
                }
                break;
            //消息页面
            case R.id.img_news:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent Nintent = new Intent(getActivity(), NewsActivity.class);
                    startActivity(Nintent);
                } else {
                    showLoginPopupWindow();
                }

                break;
            //申请提现
            case R.id.ll_tixian:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent RWintent = new Intent(getActivity(), RequestWithdrawActivity.class);
                    if (data != null) {
                        RWintent.putExtra("data", data.getBalance());
                    }
                    startActivity(RWintent);
                } else {
                    showLoginPopupWindow();
                }

                break;
            //我的推荐人
            case R.id.ll_up_people:
                Intent mupintent = new Intent(getActivity(), MyUpPeopleActivity.class);
                mupintent.putExtra("data", data.getMySuperior());
                startActivity(mupintent);
                break;
            //我的售后
            case R.id.ll_shouhou:

                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    Intent mspintent = new Intent(getActivity(), ShouHouActivity.class);
                    startActivity(mspintent);
                } else {
                    showLoginPopupWindow();
                }


                break;
            //申请城市合伙人
            case R.id.llPartner:

                startActivity(new Intent(getActivity(), PartnerApplicationActivity.class));
              /*  if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    if ("1".equals(mCheck)) {
                        Intent intent = new Intent(getActivity(), CityPartnerActivity.class);
                        startActivity(intent);
                    } else if ("0".equals(mCode) && !"1".equals(mCheck)) {
                        startActivity(new Intent(getActivity(), ApplicationActivity.class));

                    } else if (!"0".equals(mCode)) {
                        startActivity(new Intent(getActivity(), ApplicationActivity.class));
                    }
                } else {
                    showLoginPopupWindow();
                }*/
                break;

            case R.id.ll_group_profit:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    //跳转拼团收益:
                    Intent intent = new Intent(getActivity(), GroupingProfitActivity.class);
                    startActivity(intent);
                } else {
                    showLoginPopupWindow();
                }

                break;

            case R.id.ll_order_manage:
                if (!"".equals(MyApp.loginMessage.getString("token", ""))) {
                    //跳转订单管理
                    Intent intent3 = new Intent(getActivity(), OrderManageActivity.class);
                    startActivity(intent3);
                } else {
                    showLoginPopupWindow();
                }
                break;
        }
    }

    private void showLoginPopupWindow() {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_login, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), NewLoginActivity.class));
                SharedPreferences.Editor editor = MyApp.loginMessage.edit();
                editor.putString("token", "");
                editor.putString("personNickname", "");
                editor.putString("personAvatar", "");
                editor.putString("personBirth", "");
                editor.putString("personGender", "");
                editor.putString("shopname", "");
                editor.putString("shoplogo", "");
                editor.putString("shopimg", "");
                editor.putString("shopDescription", "");
                editor.putString("recommendName", "");
                editor.putString("isagent","");
                editor.apply();
                finishAllActivity();
                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.frg_my2, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    /**
     * 展示界面
     */
    private void showView() {
        if (!"1".equals(MyApp.loginMessage.getString("isagent" , ""))) {
           mL.setVisibility(View.GONE);
          mLl.setVisibility(View.GONE);
        } else {
            mL.setVisibility(View.VISIBLE);
            mLl.setVisibility(View.VISIBLE);

        }

        if (data.getAvatar() != null && !"".equals(data.getAvatar())) {
            Picasso.with(MyApp.context).load(data.getAvatar()).placeholder(R.mipmap.zhanweitu2).into(ivtouxiang);
        }
        tvname.setText(data.getNickname());
        //  tv_shopNum.setText(data.getCartCount());

        if (data.getBalance() != null && !"".equals(data.getBalance())) {
            tvkeyong.setText(NumberUtils.DecimalFormat(data.getBalance()));
        }
        if (data.getBrokerage() != null && !"".equals(data.getBrokerage())) {
            tvleiji.setText(NumberUtils.DecimalFormat(data.getBrokerage()));
        }
        if (data.getBrokerage1() != null && !"".equals(data.getBrokerage1())) {
            tvdaifa.setText(NumberUtils.DecimalFormat(data.getBrokerage1()));
        }
        if (ASUtils.isCanUse(data.getProfitsManage())) {
            //  tvguanli.setText(NumberUtils.DecimalFormat(data.getProfitsManage()));
        }

        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("personNickname", data.getNickname());
        editor.putString("personAvatar", data.getAvatar());
        editor.apply();

    }

    /**
     * @param object 获取资料成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        data = (UserInfo_Data) object;
        //城市合伙人  else llPartner.setVisibility(View.GONE);改成VISIBLE
        if ("1".equals(data.getIscitypartner())) {
            llPartner.setVisibility(View.VISIBLE);
        } else llPartner.setVisibility(View.VISIBLE);

     /*   if (ASUtils.isCanUse(data.getShopertime())) {
            tvtime.setText(DateUtil.miao2day(data.getShopertime()) + "天");
        } else {
            tvtime.setText("已到期");
        }*/
        if (data.getMySuperior() != null) {
            lluppeople.setVisibility(View.VISIBLE);
            // textView.setVisibility(View.VISIBLE);
        } else {
            lluppeople.setVisibility(View.INVISIBLE);
            //  textView.setVisibility(View.GONE);
        }
        showView();
    }

    /**
     * @param object 获取资料失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 获取未读消息成功
     */
    @Override
    public void getNewsNumberSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        int num = jsonObject.optInt("res");
        badgeView.setTargetView(view.findViewById(R.id.img_news));
        badgeView.setBadgeMargin(0, 10, 10, 0);
        badgeView.setBadgeCount(num);
    }

    /**
     * @param object 获取未读消息失败
     */
    @Override
    public void getNewsNumberError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("message"));
    }

    @Override
    public void onRefresh() {
        model.getData(this);
        model.getNewNumber(this);
    }

    @Override
    public void beCityPartnersSuccess(Object object) {

        mPartnersData = (BeCityPartnersData) object;
        ShowViews();
    }

    private void ShowViews() {
        mCode = mPartnersData.getCode();
        mCheck = mPartnersData.getCheck();
        mIspay = mPartnersData.getIspay();
    }

    @Override
    public void beCityPartnersError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);

    }
}
